import urllib
import cherrypy

from message import Message
from connection import MysqlConnection

'''
  Decorators
  Determine which method should be exposed
'''
def expose(method):
  def replacement_method(self, *args, **kwargs):
    return_value = method(self, *args, **kwargs)
    return return_value
  replacement_method.exposed = True
  return replacement_method

'''
This WebLayer behaves like web-service server.
It's instance is daemonize by web_start.py script in /bin folder
'''
class WebLayer(object):
  def get_db_config(self):
    default = {'host':'localhost', 'user':'root', 'password':'', 'core_db':'sms_db'}
    return cherrypy.config.get('db', default)
    
  @expose
  def index(self):
    pass
    
  @expose
  def send(self, global_unique_id, content=None):
    if len(global_unique_id) != 40:
      return str(Message.STATUS_FAILED)
    try:
      # We receive content, yay!
      if content:
        # decode/unquote the content
        content = urllib.unquote(content)
        
        # Create db connection
        MysqlConnection(self.get_db_config())
        
        # create the message object so that it can be inserted to database
        message = Message.create(content, Message.DIRECTION_IN, global_unique_id)
        if message:
          message.status = Message.STATUS_SUCCESS
          message.sync()
          return str(Message.STATUS_SUCCESS)
        else:
          return str(Message.STATUS_FAILED)
    except Exception, e:
      return str(Message.STATUS_FAILED)